import wsgiref.handlers
import sys
import os
import string
import codecs
import random
import re
import cgi
import datetime
import time
import math
import pickle
import logging

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
LIB_PATH = os.path.join(DIR_PATH, "lib")
EXTRA_PATHS = []
for path in os.listdir(LIB_PATH):
    fullpath = os.path.join(LIB_PATH, path)
    if os.path.isdir(fullpath) and not path.startswith("."):
        EXTRA_PATHS.append(fullpath)
sys.path = sys.path + EXTRA_PATHS

from google.appengine.api import mail
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import search
from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.api import urlfetch
from datetime import datetime, timedelta
from django.core import serializers
from django.http import HttpResponsePermanentRedirect
from google.appengine.api import users
from google.appengine.api import memcache
from google.appengine.api import images 
from google.appengine.ext.db import GqlQuery
from models import *
from utilities import *


webapp.template.register_template_library('customfilters')



class ArticleAction(webapp.RequestHandler):
  def get(self,articleid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     article = Article.get(articleid)
     article.delete()
     self.redirect("/admin/articles/")
     return 1
   elif action=='edit':
     article=Article.get(articleid)
     queryfiles = File.all()
     queryfiles.filter('filekey = ', articleid)
     images = queryfiles.fetch(3)
     queryarticlecategories = ArticleCategory.all()
     queryarticlecategories.order('name')
     categories = queryarticlecategories.fetch(500)
     template_values = {
       'article': article,
       'filekey': articleid,
       'images': images,
       'categories': categories,
       'path': "/admin/articles/" + articleid + "/save/",
     }
   elif action=='new':
     queryarticlecategories = ArticleCategory.all()
     queryarticlecategories.order('name')
     categories = queryarticlecategories.fetch(500)
     template_values = {
       'path': "/admin/articles//save/",
       'categories': categories
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/article.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,articleid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if articleid!='':
       article=Article.get(articleid)
     else:
       article = Article()
     if self.request.get("save")!='':
       title = self.request.get("title")
       url = self.request.get("url")
       align = self.request.get("align")
       category = self.request.get("category")
       codenum = self.request.get("codenum")
       body = self.request.get("body")
       error = False
       if error:
         article=Article.get(articleid)
         queryfiles = File.all()
         queryfiles.filter('filekey = ', articleid)
         images = queryfiles.fetch(3)
         queryarticlecategories = ArticleCategory.all()
         queryarticlecategories.order('name')
         categories = queryarticlecategories.fetch(500)
         template_values = {
           'article': article,
           'images': images,
           'categories': categories,
           'path': "/admin/articles/"+articleid+"/save/",
         }
         path = os.path.join(os.path.dirname(__file__), 'admin/article.html')
         self.response.out.write(template.render(path, template_values))
       else:
         article.title = title
         article.url = url
         article.alignimage = align
         article.category = ArticleCategory.get(category)
         article.body = body
         article.put()
         queryfiles = File.all()
         queryfiles.filter('filekey = ', codenum)
         files = queryfiles.fetch(10)
         for afile in files:
           afile.filekey=str(article.key())
           afile.status='a'
           afile.put()
           if afile.imagetype=='article':
             article.imagekey = str(afile.key())
             article.put()

         article.put()
         self.redirect("/admin/articles/")



class ArticleCategoryAction(webapp.RequestHandler):
  def get(self,articlecategoryid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     articlecategory=ArticleCategory.get(articlecategoryid)
     articlecategory.delete()
     self.redirect("/admin/articlecategories/", False)
     return 1
   elif action=='edit':
     articlecategory=ArticleCategory.get(articlecategoryid)
     template_values = {
       'articlecategory': articlecategory,
       'filekey': articlecategoryid,
       'path': "/admin/articlecategories/"+articlecategoryid+"/save/",
     }
   elif action=='new':
     template_values = {
       'path': "/admin/articlecategories//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/articlecategory.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,articlecategoryid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if articlecategoryid!='':
       articlecategory=ArticleCategory.get(articlecategoryid)
     else:
       articlecategory = ArticleCategory()

     if self.request.get("save")!='':
       url = self.request.get("url")
       name = self.request.get("name")
       description = self.request.get("description")

       articlecategory.url = url
       articlecategory.name = name
       articlecategory.description = description
       articlecategory.put()

     self.redirect("/admin/articlecategories/", True)



class ArticleCategoryList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryarticlecategories = ArticleCategory.all()
   queryarticlecategories.order('name')
   articlecategories = queryarticlecategories.fetch(500)
   for category in articlecategories:
     queryarticles = Article.all()
     queryarticles.filter(' category = ', category)
     queryarticles.order('-pub_date')
     category.articlescounter = queryarticles.count(10)
     category.put()


   template_values = {
     'articlecategories': articlecategories
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/articlecategories.html')
   self.response.out.write(template.render(path, template_values))



class ArticleList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryarticles = Article.all()
   queryarticles.order('title')
   articles = queryarticles.fetch(500)
   template_values = {
     'articles': articles
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/articles.html')
   self.response.out.write(template.render(path, template_values))



class DeleteImage(webapp.RequestHandler):
  def post(self,key):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    user = users.get_current_user()
    myfile=File.get(key)
    code = myfile.code
    imagetype = myfile.imagetype
    queryfiles=File.all()
    queryfiles.filter('code = ',myfile.code)
    queryfiles.filter('filekey = ',myfile.filekey)
    deletedfiles = queryfiles.fetch(10)
    for afile in deletedfiles:
      afile.delete()

    template_values = {
      'status': 5,
      'code': code,
      'type': imagetype
    }
    path = os.path.join(os.path.dirname(__file__), 'admin/checkimage.json')
    self.response.out.write(template.render(path, template_values))



class Index(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   self.redirect("/admin/linkcategories/", True)



class LinkCategoryAction(webapp.RequestHandler):
  def get(self,linkcategoryid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     linkcategory=LinkCategory.get(linkcategoryid)
     linkcategory.delete()
     self.redirect("/admin/linkcategories/", False)
     return 1
   if action=='deleteall':
     linkcategory=LinkCategory.get(linkcategoryid)
     querylinks = Link.all()
     querylinks.filter(' linkcategory = ',linkcategory)
     links = querylinks.fetch(500)
     for link in links:
       link.delete()
     self.redirect("/admin/links/"+linkcategoryid+'/', False)
     return 1
   elif action=='edit':
     linkcategory=LinkCategory.get(linkcategoryid)
     queryfiles = File.all()
     queryfiles.filter('filekey = ', linkcategoryid)
     images = queryfiles.fetch(3)
     template_values = {
       'linkcategory': linkcategory,
       'filekey': linkcategoryid,
       'images': images,
       'path': "/admin/linkcategories/"+linkcategoryid+"/save/",
     }
   elif action=='new':
     codenum = str(random.randint(10000000,99999999))
     template_values = {
       'filekey': codenum,
       'path': "/admin/linkcategories//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/linkcategory.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,linkcategoryid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if linkcategoryid!='':
       linkcategory=LinkCategory.get(linkcategoryid)
     else:
       linkcategory = LinkCategory()

     if self.request.get("save")!='':
       url = self.request.get("url")
       try:
         order = int(self.request.get("order"))
       except :
         order = 0

       codenum = self.request.get("codenum")
       name = self.request.get("name")
       structure = self.request.get("structure")
       description = self.request.get("description")

       linkcategory.url = url
       linkcategory.order = order
       linkcategory.name = name
       linkcategory.structure = structure
       linkcategory.description = description
       linkcategory.put()

       queryfiles = File.all()
       queryfiles.filter('filekey = ', codenum)
       files = queryfiles.fetch(10)
       for afile in files:
         afile.filekey=str(linkcategory.key())
         afile.status='a'
         afile.put()
         if afile.imagetype=='muestra':
           linkcategory.imagekey = str(afile.key())
           linkcategory.put()

     self.redirect("/admin/linkcategories/", True)



class LinkAction(webapp.RequestHandler):
  def get(self,linkid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     link=Link.get(linkid)
     link.delete()
     self.redirect("/admin/links/", False)
     return 1
   elif action=='edit':
     link=Link.get(linkid)
     queryfiles = File.all()
     queryfiles.filter('filekey = ', linkid)
     images = queryfiles.fetch(3)
     querylinkcategories = LinkCategory.all()
     linkcategories = querylinkcategories.fetch(50)
     queryunits = Unit.all()
     units = queryunits.fetch(50)
     template_values = {
       'link': link,
       'linkcategories': linkcategories,
       'units': units,
       'filekey': linkid,
       'images': images,
       'path': "/admin/links/"+linkid+"/save/",
     }
   elif action=='new':
     codenum = str(random.randint(10000000,99999999))
     querylinkcategories = LinkCategory.all()
     linkcategories = querylinkcategories.fetch(50)
     queryunits = Unit.all()
     units = queryunits.fetch(50)
     template_values = {
       'filekey': codenum,
       'path': "/admin/links//save/",
       'linkcategories': linkcategories,
       'units': units,
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/link.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,linkid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if linkid!='':
       link=Link.get(linkid)
     else:
       link = Link()

     if self.request.get("save")!='':
       url = self.request.get("url")
       try:
         order = int(self.request.get("order"))
       except :
         order = 0

       codenum = self.request.get("codenum")
       category = self.request.get("category")
       unit = self.request.get("unit")
       name = self.request.get("name")
       href = self.request.get("href")
       difficulty = self.request.get("difficulty")
       activity = self.request.get("activity")
       description = self.request.get("description")
       if unit != '':
         linktype = 'unit'
       else:
         linktype = 'category'

       link.url = url
       link.order = order
       link.name = name
       link.href = href
       link.difficulty = difficulty
       link.activity = activity
       link.linktype = linktype
       if linktype == 'category':
         if category != '':
           link.category = LinkCategory.get(category)
         else:
           link.category = None
       else:
         if unit != '':
           link.unit = Unit.get(unit)
         else:
           link.unit = None
       link.description = description
       link.put()

       queryfiles = File.all()
       queryfiles.filter('filekey = ', codenum)
       files = queryfiles.fetch(10)
       for afile in files:
         afile.filekey=str(link.key())
         afile.status='a'
         afile.put()
         if afile.imagetype=='muestra':
           link.imagekey = str(afile.key())
           link.put()

     self.redirect("/admin/links/", True)



class LinkList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   querylinks = Link.all()
   querylinks.order('name')
   links = querylinks.fetch(500)
   template_values = {
     'links': links
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/links.html')
   self.response.out.write(template.render(path, template_values))



class LinkCategoryList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   querylinkcategories = LinkCategory.all()
   querylinkcategories.order('name')
   linkcategories = querylinkcategories.fetch(500)
   template_values = {
     'linkcategories': linkcategories
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/linkcategories.html')
   self.response.out.write(template.render(path, template_values))



class TodoList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   querytodos = Todo.all()
   querytodos.filter('done = ', False)
   querytodos.order('-pub_date')  
   todos=querytodos.fetch(100)
   template_values = {
     'todos': todos
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/todolist.html')
   self.response.out.write(template.render(path, template_values))

  def post(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   action = self.request.get("action")
   path = os.path.join(os.path.dirname(__file__), 'admin/todolist.json')
   user = users.get_current_user()
   username = user.nickname()
   if action=='save':
     title = self.request.get("title").replace('\n','<br />').replace('"',"'")
     description = self.request.get("description").replace('\n','<br />').replace('"',"'")
     department = self.request.get("department")
     if title!='':
       todo = Todo()
       todo.title = title
       todo.description = description
       todo.department = department
       todo.creator = username
       todo.done=False
       todo.put()
       todos = []
       todos.append(todo)
       message = mail.EmailMessage(sender="averdion@gmail.com",subject="New task: " + todo.title)
       message.to = "zazuteam@googlegroups.com"
       txtbody= todo.description + "\n\nAdded by: " + todo.creator + "\n\n"
       txtbody += "Category: "+todo.department + "\n\nhttp://ociowatch.appspot.com/admin/todolist/"
       message.body = txtbody
       status = 'save'
       #try:
         #message.send()
       #except :
         #p=0
     else:
       status='notsave'
       todos = []
       todos.append('todo')
     template_values = {
       'counterpendings': 0,
       'counterdones': 0,
       'todos': todos,
       'status': status,
       'username': username
     }
     stroutput = template.render(path, template_values)
   elif action=='done':
     todo=Todo.get(self.request.get("key"))
     todo.done = True
     todo.put()
     todos = []
     todos.append(todo)
     message = mail.EmailMessage(sender="averdion@gmail.com",subject="Task done: " + todo.title)
     message.to = "zazuteam@googlegroups.com"
     txtbody = "Category: " + todo.department + ".\n\n"
     txtbody += "A otra cosa mariposa :)\n\nhttp://ociowatch.appspot.com/admin/todolist/\n\n " + todo.description
     message.body = txtbody
     try:
       message.send()
     except :
       p=0
     template_values = {
       'counterpendings': 0,
       'counterdones': 0,
       'todos': todos,
       'status': 'done',
       'username': username
     }
     stroutput = template.render(path, template_values)
   elif action=='remove':
     todo=Todo.get(self.request.get("key"))
     todos = []
     todos.append(todo)
     template_values = {
       'counterpendings': 0,
       'counterdones': 0,
       'todos': todos,
       'status': 'remove',
       'username': username
     }
     stroutput = template.render(path, template_values)
     todo.delete()
   elif action=='lock':
     todo=Todo.get(self.request.get("key"))
     if todo.locker=='':
       todo.locker = username
     else:
       todo.locker = ''
     todo.put()
     todos = []
     todos.append(todo)
     template_values = {
       'counterpendings': 0,
       'counterdones': 0,
       'todos': todos,
       'status': 'lock',
       'username': username
     }
     stroutput = template.render(path, template_values)
   elif action=='loaddone':
     querytodos = Todo.all()
     querytodos.filter('done = ', True)
     department = self.request.get("txtdepartment")
     if department!='':
       querytodos.filter('department = ', department)     
     querytodos.order('-pub_date')  
     todos=querytodos.fetch(100)
     counterdones = querytodos.count(100)
     for todo in todos:
       todo.description = todo.description.replace('\n','');
     template_values = {
       'counterpendings': 0,
       'counterdones': counterdones,
       'counterdones': 0,
       'todos': todos,
       'status': 'loaddone',
       'username': username
     }
     stroutput = template.render(path, template_values)
   elif action=='loadpending':
     querytodos = Todo.all()
     querytodos.filter('done = ', False)
     department = self.request.get("txtdepartment")
     if department!='':
       querytodos.filter('department = ', department)
     querytodos.order('-pub_date')  
     todos=querytodos.fetch(100)
     counterpendings = querytodos.count(100)
     for todo in todos:
       todo.description = todo.description.replace('\n','');
     template_values = {
       'counterpendings': counterpendings,
       'counterdones': 0,
       'counterdones': 0,
       'todos': todos,
       'status': 'loadpending',
       'username': username
     }
     stroutput = template.render(path, template_values)
   elif action=='initcounters':
     department = self.request.get("txtdepartment")
     querytodos = Todo.all()
     querytodos.filter('done = ', True)
     if department!='':
       querytodos.filter('department = ', department)
     querytodos.order('-pub_date')
     counterdones=querytodos.count(100)
     mode=2

     querytodos = Todo.all()
     querytodos.filter('done = ', False)
     if department!='':
       querytodos.filter('department = ', department)
     querytodos.order('-pub_date')  
     counterpendings=querytodos.count(100)
     todos = []
     todos.append(querytodos.fetch(1))
     template_values = {
       'counterpendings': counterpendings,
       'counterdones': counterdones,
       'todos': todos,
       'status': 'initcounters',
       'username': username
     }
     stroutput = template.render(path, template_values)
   
   self.response.out.write(stroutput)



class UnitAction(webapp.RequestHandler):
  def get(self,unitid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   if action=='delete':
     unit=Unit.get(unitid)
     unit.delete()
     self.redirect("/admin/units/", False)
     return 1
   if action=='deleteall':
     unit=Unit.get(unitid)
     querylinks = Link.all()
     querylinks.filter(' unit = ',unit)
     links = querylinks.fetch(500)
     for link in links:
       link.delete()
     self.redirect("/admin/links/"+unitid+'/', False)
     return 1
   elif action=='edit':
     unit=Unit.get(unitid)
     queryfiles = File.all()
     queryfiles.filter('filekey = ', unitid)
     images = queryfiles.fetch(3)
     template_values = {
       'unit': unit,
       'filekey': unitid,
       'images': images,
       'path': "/admin/units/"+unitid+"/save/",
     }
   elif action=='new':
     codenum = str(random.randint(10000000,99999999))
     template_values = {
       'filekey': codenum,
       'path': "/admin/units//save/",
     }
   path = os.path.join(os.path.dirname(__file__), 'admin/unit.html')
   self.response.out.write(template.render(path, template_values))
     
  def post(self,unitid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]

   if action=='save':
     if unitid!='':
       unit = Unit.get(unitid)
     else:
       unit = Unit()

     if self.request.get("save")!='':
       url = self.request.get("url")
       try:
         order = int(self.request.get("order"))
       except :
         order = 0

       codenum = self.request.get("codenum")
       name = self.request.get("name")
       structure = self.request.get("structure")
       description = self.request.get("description")

       unit.url = url
       unit.order = order
       unit.name = name
       unit.structure = structure
       unit.description = description
       unit.put()

       queryfiles = File.all()
       queryfiles.filter('filekey = ', codenum)
       files = queryfiles.fetch(10)
       for afile in files:
         afile.filekey=str(unit.key())
         afile.status='a'
         afile.put()
         if afile.imagetype=='muestra':
           unit.imagekey = str(afile.key())
           unit.put()

     self.redirect("/admin/units/", True)



class UnitList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   queryunits = Unit.all()
   queryunits.order('name')
   units = queryunits.fetch(500)
   template_values = {
     'units': units
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/units.html')
   self.response.out.write(template.render(path, template_values))



class UploadFile(webapp.RequestHandler):
  def get(self,kind,filekey,callback):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    imagekey=""
    service = self.request.get('service')
    imagetype = self.request.get('imagetype')
    template_values = {
      'error': '',
      'kind': kind,
      'filekey': filekey,
      'callback': callback,
      'service': service,
      'imagetype': imagetype
    }
    path = os.path.join(os.path.dirname(__file__), 'admin/fileupload.html')
    self.response.out.write(template.render(path, template_values))

  def post(self,kind,filekey,callback):
    logincontrol = LoginControl()
    access = logincontrol.CheckLogin('admin',self)
    url = self.request.get("url")
    item = self.request.POST.get('fileupload')
    service = self.request.get('service')
    imagetype = self.request.get('imagetype')

    if url=='':
      file_content=item.file.read()
      content=db.Blob(file_content)
      service='uploaded'
    elif url!='':
      try:
        result = urlfetch.fetch(url)
        content=db.Blob(result.content)
        service='urlfetch'
      except:
        error = " The image cannot be loaded, maybe it was a too heavy image"
        template_values = {
          'error': error,
          'kind': kind,
          'filekey': filekey,
          'posted': True,
          'callback': callback,
          'service': service,
          'imagetype': imagetype
        }
        path = os.path.join(os.path.dirname(__file__), 'admin/fileupload.html')
        self.response.out.write(template.render(path, template_values))
        return 0
    else:
      self.redirect("/admin/upload/"+kind+"/"+filekey+"/"+callback+"/", True)
      return False

    myfile = File()
    img=images.Image(content)
    myfile.bytes_content = content
    myfile.code=str(random.randint(10000000,99999999))
    user = users.get_current_user()
    myfile.mime = "image/jpg"
    myfile.extension = 'jpg'
    myfile.size = 0
    myfile.height = img.height
    myfile.width = img.width
    myfile.status = 'd'
    myfile.type = kind
    myfile.imagetype = imagetype
    myfile.service = service
    myfile.filekey = str(filekey)
    myfile.put()
    template_values = {
      'error': '',
      'kind': kind,
      'filekey': str(myfile.key()),
      'posted': True,
      'callback': callback,
      'service': service,
      'imagetype': imagetype
    }
    path = os.path.join(os.path.dirname(__file__), 'admin/fileupload.html')
    self.response.out.write(template.render(path, template_values))



class UserAction(webapp.RequestHandler):
  def get(self,customuserid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   #access = 1
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   if len(customusers) > 0:
     customuser = customusers[0]
   else:
     customuser = 1
   if action=='delete':
     customuser=CustomUser.get(customuserid)
     customuser.delete()
     self.redirect("/admin/users/", True)
     return 1
   elif action=='new':
     template_values = {
       'path': "/admin/users//save/",
     }
   elif action=='edit':
     customuser=CustomUser.get(customuserid)
     template_values = {
       'customuser': customuser,
       'path': "/admin/users/"+str(customuser.key())+"/save/",
     }

   path = os.path.join(os.path.dirname(__file__), 'admin/user.html')
   self.response.out.write(template.render(path, template_values))


  def post(self,customuserid,action):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   access = 1
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   if len(customusers) > 0:
     customuser = customusers[0]
   else:
     customuser = 1

   if  action=="save":
     if self.request.get("save")!="":
       if customuserid!='':
         customuser=CustomUser.get(customuserid)
       else:
         customuser=CustomUser()
       error=False
       message="error"
     #if self.request.get("author")=="":
      # error=True
       #message+="You must indicate your name<br/>"
     #if self.request.get("email")=="":
       #error=True
       #message+="You must indicate your email<br/>"
     #if self.request.get("email").find("@")==-1 :
       #error=True
       #message+="You must indicate a valid email<br/>"
     #if self.request.get("message")=="":
       #error=True
       #message+="You must write a comment"

     if error :
        template_values = {
        		'customuser': customuser,
        		'path': "/admin/users/"+str(customuser.key())+"/save/",
        }

        path = os.path.join(os.path.dirname(__file__), 'admin/user.html')
        self.response.out.write(template.render(path, template_values))
     else:
       name=self.request.get("name")
       url=self.request.get("url")
       role=self.request.get("role")
       email=self.request.get("email")
       customuser.name = name
       customuser.role = role
       customuser.url = url
       customuser.user = users.User(email = email)
       customuser.put()
       template_values = {
       	'customuser': customuser,
       	'path': "/admin/users/"+str(customuser.key())+"/save/",
       }

       self.redirect("/admin/users/", True)



class UsersList(webapp.RequestHandler):
  def get(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   #access = 1
   if access==0:
     return 0
   user = users.get_current_user()
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   if len(customusers) > 0:
     customuser = customusers[0]
   else:
     customuser = 1
   queryusers=CustomUser.all()
   queryusers.order("name")
   customusers=queryusers.fetch(50)
   template_values = {
     'customusers': customusers,
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/users.html')
   self.response.out.write(template.render(path, template_values))

  def post(self):
   logincontrol = LoginControl()
   access = logincontrol.CheckLogin('admin',self)
   if access==0:
     return 0
   queryuser = CustomUser.all()
   queryuser.filter(' user = ', user)
   customusers = queryuser.fetch(1)
   customuser = customusers[0]
   searchtext=self.request.get("busqueda")
   if self.request.get("page")=='':
   	page=0
   else:
   	page=int(self.request.get("page"))

   offset=page*20
   queryusers=CustomUser.all().search(searchtext)
   queryusers.order('name')     
   customusers=queryusers.fetch(50,offset)

   template_values = {
     'customusers': customusers,
     'page': page,
   }
   path = os.path.join(os.path.dirname(__file__), 'admin/users.html')
   self.response.out.write(template.render(path, template_values))



def main():
  application = webapp.WSGIApplication([('/admin/', Index),
                                        ('/admin/links/(.*)/(edit)/', LinkAction),
                                        ('/admin/links/(.*)/(new)/', LinkAction),
                                        ('/admin/links/(.*)/(save)/', LinkAction),
                                        ('/admin/links/(.*)/(delete)/', LinkAction),
                                        ('/admin/links/', LinkList),
                                        ('/admin/linkcategories/(.*)/(edit)/', LinkCategoryAction),
                                        ('/admin/linkcategories/(.*)/(new)/', LinkCategoryAction),
                                        ('/admin/linkcategories/(.*)/(save)/', LinkCategoryAction),
                                        ('/admin/linkcategories/(.*)/(delete)/', LinkCategoryAction),
                                        ('/admin/linkcategories/', LinkCategoryList),
                                        ('/admin/units/(.*)/(edit)/', UnitAction),
                                        ('/admin/units/(.*)/(new)/', UnitAction),
                                        ('/admin/units/(.*)/(save)/', UnitAction),
                                        ('/admin/units/(.*)/(delete)/', UnitAction),
                                        ('/admin/units/', UnitList),
                                        ('/admin/articles/(.*)/(edit)/', ArticleAction),
                                        ('/admin/articles/(.*)/(new)/', ArticleAction),
                                        ('/admin/articles/(.*)/(save)/', ArticleAction),
                                        ('/admin/articles/(.*)/(delete)/', ArticleAction),
                                        ('/admin/articlecategories/(.*)/(edit)/', ArticleCategoryAction),
                                        ('/admin/articlecategories/(.*)/(new)/', ArticleCategoryAction),
                                        ('/admin/articlecategories/(.*)/(save)/', ArticleCategoryAction),
                                        ('/admin/articlecategories/(.*)/(delete)/', ArticleCategoryAction),
                                        ('/admin/users/(.*)/(edit)/', UserAction),
                                        ('/admin/users/(.*)/(new)/', UserAction),
                                        ('/admin/users/(.*)/(save)/', UserAction),
                                        ('/admin/users/(.*)/(delete)/', UserAction),
                                        ('/admin/users/', UsersList),
                                        ('/admin/articlecategories/', ArticleCategoryList),
                                        ('/admin/articles/', ArticleList),
                                        ('/admin/todolist/', TodoList),
                                        ('/admin/todolist', TodoList),
                                        ('/admin/upload/(.*)/(.*)/(.*)/', UploadFile),
                                        ('/admin/image/delete/(.*)/', DeleteImage),
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
